<?php
/*
 * 系统设置
 */
namespace Admin\Controller;
use Admin\Model\configModel;
use Admin\Model\focusModel;
use Admin\Model\expresscomModel;
use Admin\Model\bankcomModel;

class SystemController extends BaseController {
    
    public $focusModel;
    public $expresscomModel;
    public $bankcomModel;
	public $keywordsModel;
    
    public function __construct() {
        parent::__construct();
        $this->keywordsModel = M('wxkeywords');
        if($this->admininfo['role_id'] != 1){
//            $this->error("抱歉,仅超级管理员才可以编辑系统信息");
        }
    }
    
    /*
     * 基本设置
     */
    public function index(){
        if(IS_AJAX){
            $data =  param_filter($_POST,array('IS_CLOSED','DEBUG_UID','CLOSED_REASON','QRCODE_PAY','BUTTON_PAY'),array('IS_CLOSED','CLOSED_REASON'),$filter=true);//过滤数据
            if(!empty($data)){
                $res = $this->_setConfig($data);
                return_json(0,"设置成功");
            }
            return_json(1,"设置失败");
        }
        $this->display();
    }
    
    /*
     * seo设置
     */
    public function seo(){
        if(IS_AJAX){
            
            $allow = array(
                'SHARE_DEFAULT_TITLE',
                'SHARE_DEFAULT_DESC',
                'SUBSCRIBE_URL',
                "SITE_NAME",
                "SITE_COMPANY",
                "SITE_TEL",
                "SITE_ICP",
                "GUESTBOOK_UID",
                "PUTONG_QRCODE"
            );
            
            $must = array('SHARE_DEFAULT_TITLE','SHARE_DEFAULT_DESC','SUBSCRIBE_URL',"SITE_NAME");
            
            $data =  param_filter($_POST,$allow,$must,$filter=true);//过滤数据
            if(!empty($data)){
                $res = $this->_setConfig($data);
                return_json(0,"设置成功");
            }
            return_json(1,"设置失败");
        }
        $this->display();
    }
    
    
    /*
     * seo设置
     */
    public function order(){
        if(IS_AJAX){
            $allow = array(
                'CLOSE_ORDER_TIME',"FAHUO_ADS","FAHUO_NOTE",
                "FAHUO_ADDRESS","FAHUO_DANWEI","FAHUO_TEL",
                "FAHUO_CONTACT","NOTFULL_BAOYOU","FULL_BAOYOU","YONGJIN_LOCK",
                "ORDER_ADMIN_UIDS","BUHUO_NUM","TIHUO_NUM",
                "GRADE2_NUM","GRADE3_NUM","GRADE4_NUM","GRADE5_NUM",
                "GRADE4_BZJ","GRADE5_BZJ","GRADE4_PXF","GRADE5_PXF","THINK_TIME"
            );
            
            $data =  param_filter($_POST,$allow,array('CLOSE_ORDER_TIME'));//过滤数据
            if(!empty($data)){
                if($data['CLOSE_ORDER_TIME']>4320 || $data['CLOSE_ORDER_TIME']<30){
                    return_json(1,"设置失败,订单未付款自动关闭的分钟数,最少不能少于30分钟,最大不能超过4320分钟");
                }
                $data["YONGJIN_LOCK"] = intval($data["YONGJIN_LOCK"]);

                $res = $this->_setConfig($data);
                return_json(0,"设置成功");
            }
            return_json(1,"设置失败");
        }
        $gradearr = M('grade')->getField('grade_id,grade_name',true);
        $this->assign('gradearr',$gradearr);
        $this->display();
    }
    
    
    
    /*
     * 修改配置
     * $data = array(
     *      "SHARE_DEFAULT_TITLE" => $value
     * );
     */
    protected function _setConfig($data){
        foreach($data as $k=>$v){
            $res = $this->configModel->editConfig(array("cname" => $k),array("cvalue"=>$v));
        }
        return true;
    }
    
    /*
     * email设置
     */
    public function email(){
        if(IS_AJAX){
            $data =  param_filter($_POST,array('SMTP_HOST','SMTP_PORT','SMTP_USER','SMTP_PASSWORD','SMTP_NICKNAME'),array('SMTP_HOST','SMTP_PORT','SMTP_USER','SMTP_PASSWORD','SMTP_NICKNAME'),$filter=true);//过滤数据
            if(!empty($data)){
                $res = $this->_setConfig($data);
                return_json(0,"邮件服务器信息设置成功");
            }
            return_json(1,"设置失败");
        }
        $this->display();
    }
    
    
    
    /*
     * 微信设置
     */
    public function wechat(){
        if(IS_POST){
            
            $allow = array('WECHAT_APPID','WECHAT_APPKEY','WECHAT_TOKEN','WECHAT_MCHID','WECHAT_PAYKEY','WECHAT_ID');
            
            $data =  param_filter($_POST,$allow,$allow,$filter=true);//过滤数据
            if(!empty($data)){
                
                $pic = $this->iupload("ghqrcode");
                
                if($pic){
                    $data['WECHAT_QRCODE'] = $pic['pic']['savepath'].$pic['pic']['savename'];
                }

                $res = $this->_setConfig($data);
                
                $this->redirect('/admin/system/wechat/');
            }
            
            $this->redirect('/admin/system/wechat/');
        }
        
        $this->display();
    }
    
    
    /*
     * logo设置
     */
    public function logo(){
        if(IS_POST){
            
            $pics = $this->iupload("logo");
            $data = array();
            $allow = array("USER_BANNER","SHARE_DEFAULT_IMG","SITE_MLOGO1","SITE_LOGINADS","SITE_TOPLOGO2","SITE_TOPLOGO1",
            'HOW_MAKE_MONEY','ARTICLE_INDEX_IMG');
            
            foreach($pics as $k=>$pic){

                if(!in_array($k, $allow)){
                    continue;
                }
                
                if($pic){
                    $data[$k] = $pic['savepath'].$pic['savename'];
                }
            }

            $res = $this->_setConfig($data);
            $this->redirect('/admin/system/logo/');

        }
    
        $this->display();
    }
    
    
    
    /*
     * 二维码图片设置
     */
    public function qrcode(){
        if(IS_POST){
            $config = array ( 
                'maxSize' => 5 * 1024 * 1024,//文件大小
                'rootPath' => '/',
                'saveName' => array ('uniqid', ''),
                'driver' => 'Qiniu',
                'driverConfig' => array (
                        'accessKey' => '3_YIyvIvi_HW_c6Neb-0oh7SjhAQMsWd3D7Gdryq',
                        'secrectKey' => 'FLC0BeZrV1Iqf8WhtvjUCtAxfzM0fCFrrxYsLoC3', 
                        'domain' => 'qiniu.vlu2.cn',
                        'bucket' => 'haiwe7', 
                 )
            );
            $Upload = new \Think\Upload($config);
            
            $pics = $Upload->upload($_FILES);
            $data = array();
            $allow = array("QRCODE_GRADE1","QRCODE_GRADE2","QRCODE_GRADE3","QRCODE_GRADE4","QRCODE_GRADE5","QRCODE_GRADE6","QRCODE_GRADE7");
            
            foreach($pics as $k=>$pic){

                if(!in_array($k, $allow)){
                    continue;
                }
                
                if($pic){
                    $data[$k] = $pic['url'];
                }
            }
            
            /* $pics = $this->iupload("qrcodebg");
            $data = array();
            $allow = array("QRCODE_GRADE1","QRCODE_GRADE2","QRCODE_GRADE3","QRCODE_GRADE4","QRCODE_GRADE5","QRCODE_GRADE6","QRCODE_GRADE7");
            
            foreach($pics as $k=>$pic){

                if(!in_array($k, $allow)){
                    continue;
                }
                
                if($pic){
                    $data[$k] = $pic['savepath'].$pic['savename'];
                }
            } */

            $res = $this->_setConfig($data);
            $this->redirect('/admin/system/qrcode/');

        }
        $gradeArr = M('grade')->order('grade_id')->select();
        $this->assign('gradeArr',$gradeArr); 
    
        $this->display();
    }
    
    
    public function yunfei(){
        
        $expressModel = M("express");
        
        if(IS_AJAX){
            
            foreach ($_POST['express'] as $k=>$v){
                
                $where = array(
                    "province_id" => $k,
                );
                
                $data = array(
                    "first_weight" => $v[0],
                    "next_weight" => $v[1],
                );
                
                $expressModel->where($where)->save($data);
                
            }
            
            //访问重新生成运费js
            curl(get_domain()."/mobile/address/createShipping");

            return_json(0,"已保存");
            
        }
        
        
        $express = $expressModel->select();
        $this->assign("express",$express);
        
        $this->display();
    }
    
    
    /*
     * 又拍云存储设置
     */
    public function upyun(){
        if(IS_AJAX){
    
            $allow = array('UPYUN_USER','UPYUN_PASSWORD','UPYUN_BUCKET','UPYUN_DOMAIN');
    
            $data =  param_filter($_POST,$allow,$allow,$filter=true);//过滤数据
            if(!empty($data)){
                $res = $this->_setConfig($data);
                return_json(0,"又拍云参数设置成功");
            }
            return_json(1,"设置失败");
        }
    
        $this->display();
    }
    
    /*
     * 乐视视频云设置
     * http://uc.lecloud.com/userView/userKeyView.do
     */
     public function letv(){
         if(IS_AJAX){
     
             $allow = array('LETV_USERID','LETV_UUID','LETV_APPKEY');
     
             $data =  param_filter($_POST,$allow,$allow,$filter=true);//过滤数据
             if(!empty($data)){
                 $res = $this->_setConfig($data);
                 return_json(0,"乐视云参数设置成功");
             }
             return_json(1,"设置失败");
         }
     
         $this->display();
     }
     
     /*
      * 短信设置
      * http://jehe.cn
      */
      public function sms(){
          if(IS_AJAX){
               
              $allow = array('ALIDAYU_SIGN','SMS_KEY','ALIDAYU_APPSEC',"ALIDAYU_APPKEY");
               
              $data =  param_filter($_POST,$allow,'',$filter=true);//过滤数据
              if(!empty($data)){
                  $res = $this->_setConfig($data);
                  return_json(0,"短信参数设置成功");
              }
              return_json(1,"设置失败");
          }
           
          $this->display();
      }
      
      /*
       * 小票打印机设置
       */
      public function dayin(){
          if(IS_AJAX){
               
              $allow = array('DAYIN_NO1','DAYIN_NO2');
               
              $data =  param_filter($_POST,$allow,'',$filter=true);//过滤数据
              if(!empty($data)){
                  $res = $this->_setConfig($data);
                  return_json(0,"小票打印机参数设置成功");
              }
              return_json(1,"设置失败");
          }
           
          $this->display();
      }
      
      /*
       * 名词名词
       */
      public function cname(){
          if(IS_AJAX){
               
              $allow = array('YONGJIN_NAME','SCORE_NAME','CASH_NAME',"XIAJI_NAME");
               
              $data =  param_filter($_POST,$allow,'',$filter=true);//过滤数据
              if(!empty($data)){
                  $res = $this->_setConfig($data);
                  return_json(0,"设置成功");
              }
              return_json(1,"设置失败");
          }
           
          $this->display();
      }
    
    /*
     * 幻灯片类表
     */
    public function slidelist(){
        $focusModel = new focusModel();
        $where = array(
            "position" => 1,
        );
        $res = $focusModel->getFocusLists($where);
        $this->assign('datalist',$res);
        $this->display();
    }
    
    
    
    /*
     * 首页幻灯片设置
     */
    public function huandengpian(){
        
        $focusModel = new focusModel();
        $id = get("focus_id");
        $where = array(
            "focus_id" => $id
        );
        
        
        if(!$id){
            return_json(1,"参数错误");
        }
        
        if(IS_POST){
            $data = param_filter($_POST,array("title","link","ord","status"),array("title","link","ord","status"));
            $pic = $this->iupload("slide");
            if($pic){
                $data['pic'] = $pic['pic']['savepath'].$pic['pic']['savename'];
            }
            
            if(!empty($data)){
                if($id){
                    $res = $focusModel->editFocus($where, $data);
                }else{
                    $res = $focusModel->addFocus($data);
                }
                
                if($res){
                    $this->redirect('/admin/system/slidelist/');
                }
                
            }
            
        }
        

        
        $res = $focusModel->getFocus($where);
        
        if($res){
            $this->assign('focus',$res);
        }else{
            $this->error("不存在");
        }
        
        $this->display();

    }
    
    /*
     * 快递公司设置
     */
    public function express(){
        
        $expresscomModel = new expresscomModel();
        
        if(IS_AJAX){
            $data =  $_POST;//过滤数据
            if(is_set($data, 'data')){
                
                //设置不保留下来的
                $where = array(
                    "eid" => array("NOT IN",$data['data'])
                );
                $new_data = array(
                    "status" => 0
                );
                $r1 = $expresscomModel->editExpresscom($where, $new_data);
                
                //设置排序
                foreach ($data['data'] as $k=>$v){
                    $where = array(
                        "eid" => $v,
                    );
                    $new_data = array(
                        "ord" => $k,
                        "status" => 1
                    );
                    $expresscomModel->editExpresscom($where, $new_data);
                    
                }
                return_json(0,"已保存");
            }
            return_json(1,"设置失败");
        }
        $express = $expresscomModel->getExpresscomLists();
        $this->assign('datalist',$express);
        $this->display();
    }
    
    /*
     * 银行设置
     */
    public function bank(){
    
        $bankcomModel = new bankcomModel();
    
        if(IS_AJAX){
            $data =  $_POST;//过滤数据
            if(is_set($data, 'data')){
    
                //设置不保留下来的
                $where = array(
                    "eid" => array("NOT IN",$data['data'])
                );
                $new_data = array(
                    "status" => 0
                );
                $r1 = $bankcomModel->editBankcom($where, $new_data);
    
                //设置排序
                foreach ($data['data'] as $k=>$v){
                    $where = array(
                        "eid" => $v,
                    );
                    $new_data = array(
                        "ord" => $k,
                        "status" => 1
                    );
                    $bankcomModel->editBankcom($where, $new_data);
    
                }
                return_json(0,"已保存");
            }
            return_json(1,"设置失败");
        }
        $bank = $bankcomModel->getBankcomLists("bianma>0");
        $this->assign('datalist',$bank);
        $this->display();
    }
    
    
    /*
     * 手续费提现
     */
    public function withdraw(){
        if(IS_AJAX){
             
            $allow = array('MAX_SHOUXU','WITHDRAW_RATE','WITHDRAW_DOUBLE','QIYEPAY_MONEY');
             
            $data =  param_filter($_POST,$allow,'',$filter=true);//过滤数据
            if(!empty($data)){
                $res = $this->_setConfig($data);
                return_json(0,"设置成功");
            }
            return_json(1,"设置失败");
        }
         
        $this->display();
    }
       /*
     * 自定义菜单
     */
    public function menu() {
        $this->display('Menu/index');
    }
    /*
     * 创建自定义菜单
     */
    public function createmenu(){
        //清空原来的click菜单对应关键词
        $this->keywordsModel->where("is_click = 1")->delete();
        
//        $menu = $_POST['menus'];
        $menu = htmlspecialchars_decode(stripslashes($_POST['menus']));
        $menus = json_decode($menu,true);
        foreach($menus as $key=>$val){
            if(!$val['sub_button']){
                unset($menus[$key]['sub_button']);
                if($val['type'] == 'view'){
                    unset($menus[$key]['key']);
                    unset($menus[$key]['text']);
                }else if($val['type'] == 'click'){
                    unset($menus[$key]['url']);
                    $data = array(
                        'keyword' => $menus[$key]['key'],
                        'reply_text' => $menus[$key]['text'],
                        'is_click' => 1
                    );
                    $this->keywordsModel->add($data);
                }
            }else{
                unset($menus[$key]['key']);
                unset($menus[$key]['text']);
                unset($menus[$key]['url']);
                foreach($val['sub_button'] as $k=>$v){
                    if($v['type'] == 'view'){
                        unset($menus[$key]['sub_button'][$k]['key']);
                        unset($menus[$key]['sub_button'][$k]['text']);
                    }else if($v['type'] == 'click'){
                        unset($menus[$key]['sub_button'][$k]['url']);
                        //把click 关键词  对应 text 插入数据库
                        $data = array(
                            'keyword' => $menus[$key]['sub_button'][$k]['key'],
                            'reply_text' => $menus[$key]['sub_button'][$k]['text'],
                            'is_click' => 1
                        );
                        $this->keywordsModel->add($data);
                    }
                }
            }
        }
        $res['button'] = $menus;
        if($res){
            $wechat = new \Mobile\Controller\WechatController();
            $res = $wechat->createMenu($res);
            echo $res;
        }
    }

   
    /*
     * 获取自定义菜单
     */
    public function getMenu(){
        //查出所有click事件的关键词
        $list = $this->keywordsModel->where("is_click = 1")->getField("keyword,reply_text");
        
        $wechat = new \Mobile\Controller\WechatController();
        $json = $wechat->getMenu();
        $button = $json['menu']['button'];
        //遍历button  click事件的  查出对应text
        foreach($button as $key=>$val){
            if(!$val['sub_button']){
                if($val['type'] == 'click'){
                    $button[$key]['text'] = $list[$val['key']];
                }
            }else{
                foreach($val['sub_button'] as $k=>$v){
                    if($v['type'] == 'click'){
                        $button[$key]['sub_button'][$k]['text'] = $list[$v['key']];
                    }
                }
            }
        }
        $this->ajaxReturn($button);
    }
    
    /*
     * 关键词回复
     */
    public function keyword(){
        $this->display();
    }
    public function getKeywords(){
        $click = get('click',0);
        if($click == 0){
            //普通回复
            $list = $this->keywordsModel->where("r_status = 1 AND is_click = 0")->select();
        }else if($click == 1){
            //自定义菜单click事件回复
            $list = $this->keywordsModel->where("r_status = 1 AND is_click = 1")->select();
        }
        
        $this->ajaxReturn($list);
    }
    public function addKey(){
        $data = $_POST;
        $allow = array('keyword','id','reply_text','r_type','is_jingzhun');
        $data = param_filter($data, $allow);
        if(!$data['keyword']){
            return_json(1,"保存失败，请填写关键词");
        }
        if(!$data['reply_text']){
            return_json(1,"保存失败，请填写回复内容");
        }
        if($data['id']){
            $res = $this->keywordsModel->save($data);
            if($res){
                return_json(0,"修改成功",$res);
            }
            
        }else{
            $is_allow = $this->keywordsModel->where("keyword = '".$data['keyword']."'")->find();
            //判断关键词key是否已存在
            if(!$is_allow){
                $res = $this->keywordsModel->add($data);//该条数据的id
                if($res){
                    return_json(0,"保存成功",$res);
                }
            }else{
                return_json(1,"保存失败，该关键词已存在");
            }
        }
    }
    
    public function deleteKey(){
            $data = $_POST;
            $allow = array('keyword','id','reply_text','r_type');
            $data = param_filter($data, $allow);
            if($data['id']){
                $res = $this->keywordsModel->where("id = '".$data['id']."'")->delete();
                if($res){
                    return_json(0,"删除成功");
                }
            }
        }
    
    
    
    /*
     * 充值参数设置
     */
    public function charge(){
        
        if(IS_POST){
            
            $pics = $this->iupload("caiwu");
            $data = array();
            $allow = array("CAIWU_QRCODE","PAY_TO_CAIWU");
            
            foreach($pics as $k=>$pic){

                if(!in_array($k, $allow)){
                    continue;
                }
                
                if($pic){
                    $data[$k] = $pic['savepath'].$pic['savename'];
                }
            }
            
            $data['PAY_TO_CAIWU'] = $_POST['PAY_TO_CAIWU'];

            $res = $this->_setConfig($data);
            
            $this->redirect('/admin/system/charge/');

        }
    
        $this->display();
    }
    
    
    /*
     * 证书设置
     */
    public function zhengshu(){
        if(IS_POST){
    
            
            $pics = $this->iupload("qrcodebg");
    
            $data = array();
            $allow = array("ZHENGSHU_1","ZHENGSHU_2","ZHENGSHU_3","ZHENGSHU_4","ZHENGSHU_5","ZHENGSHU_6","ZHENGSHU_7");
    
            foreach($pics as $k=>$pic){
    
                if(!in_array($k, $allow)){
                    continue;
                }
    
                if($pic){
                    $data[$k] = $pic['savepath'].$pic['savename'];
                }
            }
    
            $res = $this->_setConfig($data);
            $this->redirect('/admin/system/zhengshu/');
    
        }
        $gradeArr = M('grade')->order('grade_id')->select();
        $this->assign('gradeArr',$gradeArr);
        $this->display();
    }
    
    
    public function setTmpl(){
        
        if(IS_AJAX){
            $wechat = new \Mobile\Controller\WechatController();
            if(get('set')){
                $res = $wechat->setTMIndustry(1,2);
                if($res){
                    return_json(0,'设置行业成功');
                }else{
                    return_json(1,'设置行业失败');
                }
                
            }
            if(get('add')){
                $tmplModel = M('tmpl');
                $list = $wechat->get_all_private_template();
                foreach ($list['template_list'] as $tmp) {
                    $where = array(
                        'tmp_id' => $tmp['template_id']
                    );
                    $res = $tmplModel->where($where)->find();
                    if(!$res) {
                        $r = $wechat->del_private_template(array('template_id'=>$tmp['template_id']));
                    }
                }
                
                $tmpls = $tmplModel->field('bianhao,tmp_id')->select();
                $i = 0;
                foreach ($tmpls as $k=>$v){
                    if($v['tmp_id']) {
                        continue;
                    }
                    $id = $v['bianhao'];
                    $tmpid = $wechat->addTemplateMessage($id);
                    if($tmpid){
                        $tmplModel->where(array('bianhao'=>$id))->setField('tmp_id',$tmpid);
                        $i++;
                    }else{
                        continue;
                    }
                }
                if($i){
                    return_json(0,"模板添加完成".$i."条记录");
                }else{
                    return_json(1,'模板添加失败');
                }
                
            }
        }
        $this->display();
        
        
    }
    
    public function message () {
        if(IS_AJAX){
            $allow = array('GUESTBOOK_UID','ORDER_ADMIN_UIDS','NEW_USER_UIDS',"NEW_WITHDRAW_UIDS");
            $data =  param_filter($_POST,$allow,'',$filter=true);//过滤数据
            foreach ($data as $k=>$v) {
                $data[$k] = str_replace('，', ',', $v);
            }
            if(!empty($data)){
                $res = $this->_setConfig($data);
                return_json(0,"设置成功");
            }
            return_json(1,"设置失败");
        }
        $this->display();
    }
    
    public function ad(){
        if(IS_POST){
            $pics = $this->iupload("ad");
            $data = array();
            $allow = array('AD_IMG_URL');
            foreach($pics as $k=>$pic){
                if(!in_array($k, $allow)){
                    continue;
                }
                if($pic){
                    $data[$k] = $pic['savepath'].$pic['savename'];
                }
            }
            $data['AD_STATUS'] = $_POST['AD_STATUS'];
            $data['AD_DETAIL'] = $_POST['AD_DETAIL'];
            $data['AD_TIME'] = $_POST['AD_TIME'];
            $res = $this->_setConfig($data);
            $this->redirect('/admin/system/ad/');
        }
        C('AD_DETAIL',stripslashes(C('AD_DETAIL')));
        $this->display();
    }

    /*
   * 首页分类
   */
    public function indextype(){
        $focusModel = new focusModel();
        $where = array(
            "position" => 3,
        );
        $res = $focusModel->getFocusLists($where);
        $this->assign('datalist',$res);
        $this->display();
    }

    public function setprint(){

        if(is_ajax()){
            $save['cvalue']=I('post.PRINTER');
            $where['cname']='PRINTER';
            $configModel=new configModel();
            $re=$configModel->where($where)->save($save);
            if($re===false){
                return_json(1,'修改失败');
            }else{
                return_json(0,'修改成功');
            }
        }
        $this->display();
    }

}